﻿using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;

namespace AllMyMoney.WCFService
{
    internal sealed class I18nMessageInspector : IClientMessageInspector, IDispatchMessageInspector
    {
        public I18nMessageInspector(string locale, string timezone)
        {
            _locale = locale;
            _timezone = timezone;
        }

        //
        // IClientMessageInspector.AfterReceiveReply member
        //
        public void AfterReceiveReply(ref Message reply, object correlationState)
        {
        }

        //
        // IClientMessageInspector.BeforeSendRequest member
        //
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            International internationalHeader = new International();
            
            if(!String.IsNullOrEmpty(_locale))
                internationalHeader.Locale = _locale;

            if (!String.IsNullOrEmpty(_timezone))
                internationalHeader.Tz = _timezone;

            MessageHeader header = MessageHeader.CreateHeader("International", "http://www.w3.org/2005/09/ws-i18n", internationalHeader);
            request.Headers.Add(header);
            return null;
        }

        // 
        // IDispatchMessageInspector.AfterReceiveRequest member
        //
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            int index = request.Headers.FindHeader("International", "http://www.w3.org/2005/09/ws-i18n");
            if (index >= 0)
                request.Headers.UnderstoodHeaders.Add(request.Headers[index]);

            return null;
        }

        // 
        // IDispatchMessageInspector.BeforeSendReply member
        //
        public void BeforeSendReply(ref Message reply, object correlationState)
        {
        }

        private string _locale;
        private string _timezone;
    }
}